package admin

import (
	"errors"
	"fmt"

	"qkleague/db"
	"qkleague/errorcode"
	rpc "qkleague/rpc/client/qingke"

	"time"

	"doubimeizhi.com/datatable"
	"doubimeizhi.com/utility"
	log "github.com/cihub/seelog"
)

func (p *adminService) ListWasher(req *ShowItemReq, resp *ShowItemResp, leagueId, washRoomId, washerId string) error {
	log.Debugf("adminService-ListWasher, leagueId:%s, washRoomId:%s, washerId:%s", leagueId, washRoomId, washerId)
	dtq := p.washerDtq(leagueId, washRoomId, washerId)
	sql, val := dtq.GenerateSQL()
	mysqlHelper := db.GetQKLeagueMySQLHelper()
	results, err := mysqlHelper.Query(sql, val...)
	if err == nil {
		if len(results) == 0 {
			log.Warnf("查询没有包含此类信息的洗衣机， ListWasher, leagueId:%s, washRoomId:%s, washerId:%d", leagueId, washRoomId, washerId)
		}
		for _, dt := range results {
			li := p.washerParseRecords(mysqlHelper, dt)
			resp.Data = append(resp.Data, li)
		}
	} else {
		log.Errorf("mysql err sql:%s, err:%s", sql, err.Error())
	}

	if !req.Role {
		s, v := dtq.GenerateTotalRecordSQL("total_records")
		if results, err := mysqlHelper.Query(s, v...); err == nil {
			if len(results) > 0 {
				resp.Total = mysqlHelper.GetColInt(results[0], "total_records")
			}
		} else {
			log.Errorf("mysql err sql:%s, values:%v", err.Error(), v)
		}
	}
	if resp.Total > resp.PageSize {
		resp.HasMore = true
	}
	resp.Code = errorcode.EC_GL_SUCCESS
	resp.Msg = errorcode.Msg(errorcode.EC_GL_SUCCESS)
	resp.PageIndex = req.PageIndex
	return nil
}
func (p *adminService) ListWasherPrice(req *ShowItemReq, resp *ShowItemResp, leagueId, washRoomId, washerId string) error{
	log.Debugf("adminService-ListWasher, leagueId:%s, washRoomId:%s, washerId:%s", leagueId, washRoomId, washerId)
	dtq := p.washerDtq(leagueId, washRoomId, washerId)
	sql, val := dtq.GenerateSQL()
	mysqlHelper := db.GetQKLeagueMySQLHelper()
	results, err := mysqlHelper.Query(sql, val...)
	if err == nil {
		if len(results) == 0 {
			log.Warnf("查询没有包含此类信息的洗衣机， ListWasher, leagueId:%s, washRoomId:%s, washerId:%d", leagueId, washRoomId, washerId)
		}
		for _, dt := range results {
			li := p.washerParseRecords(mysqlHelper, dt)
			li.IsCard=p.GetIsCard(li.IMEI)
			resp.Dimei=append(resp.Dimei,li.IMEI)
			resp.Data = append(resp.Data, p.GetWasherPrice(li.WasherId,li.IsCard,li.IMEI))
			resp.DWasher=append(resp.DWasher,li.WasherId)
		}
	} else {
		log.Errorf("mysql err sql:%s, err:%s", sql, err.Error())
	}

	if !req.Role {
		s, v := dtq.GenerateTotalRecordSQL("total_records")
		if results, err := mysqlHelper.Query(s, v...); err == nil {
			if len(results) > 0 {
				resp.Total = mysqlHelper.GetColInt(results[0], "total_records")
			}
		} else {
			log.Errorf("mysql err sql:%s, values:%v", err.Error(), v)
		}
	}
	if resp.Total > resp.PageSize {
		resp.HasMore = true
	}
	resp.Code = errorcode.EC_GL_SUCCESS
	resp.Msg = errorcode.Msg(errorcode.EC_GL_SUCCESS)
	resp.PageIndex = req.PageIndex
	return nil
}
func (p *adminService) GetIsCard(imei string) int{
	sql := fmt.Sprintf("%s where imei = %s", "select is_card from washer_imei", imei)
	log.Debug(sql)
	mysqlHelper := db.GetQKLeagueMySQLHelper()
	results, err := mysqlHelper.Query(sql)
	if err == nil && len(results) > 0 {
		is_card := mysqlHelper.GetColInt(results[0], "is_card")
		return is_card
	}
	return 1
}
func (p *adminService) GetWasherPrice(washerId string,iscard int,imei string) *QKWasherPrice{
	sql := fmt.Sprintf("%s where washer_id = '%s'","SELECT washer_id,MAX(CASE wash_mode_id WHEN '4' THEN qbcoin ELSE 0 END ) qbA,MAX(CASE wash_mode_id WHEN '2' THEN qbcoin ELSE 0 END )  qbB,MAX(CASE wash_mode_id WHEN '1' THEN qbcoin ELSE 0 END )  qbC,MAX(CASE wash_mode_id WHEN '3' THEN qbcoin ELSE 0 END )  qbD,MAX(CASE wash_mode_id WHEN '4' THEN cardcoin ELSE 0 END) cardA,MAX(CASE wash_mode_id WHEN '2' THEN cardcoin ELSE 0 END) cardB,MAX(CASE wash_mode_id WHEN '1' THEN cardcoin ELSE 0 END) cardC,MAX(CASE wash_mode_id WHEN '3' THEN cardcoin ELSE 0 END) cardD FROM washing_mode",washerId)
	log.Infof("sql:%s",sql)
	mysqlHelper := db.GetQKLeagueMySQLHelper()
	results, err := mysqlHelper.Query(sql)
	log.Infof("results:%s",results)
	log.Infof("err:%s",err)
	li := &QKWasherPrice{}
	if err == nil {
		if len(results) == 0 {
			log.Warnf("查询没有包含此类信息的洗衣机 washerId:%d", washerId)
		}
		li.WasherId = mysqlHelper.GetColString(results[0], "washer_id")
		li.QBA = mysqlHelper.GetColInt(results[0], "qbA")
		li.QBB = mysqlHelper.GetColInt(results[0], "qbB")
		li.QBC = mysqlHelper.GetColInt(results[0], "qbC")
		li.QBD = mysqlHelper.GetColInt(results[0], "qbD")
		li.CardA = mysqlHelper.GetColInt(results[0], "cardA")
		li.CardB = mysqlHelper.GetColInt(results[0], "cardB")
		li.CardC = mysqlHelper.GetColInt(results[0], "cardC")
		li.CardD = mysqlHelper.GetColInt(results[0], "cardD")
		li.CardFlag=iscard
		li.Imei=imei
		log.Infof("li:%s",li)

	}
	return  li
}
func (p *adminService) ChangeWasherQBPrice(dt *QKWasherPrice ) error {
	sql := "update washing_mode set qbcoin=? where washer_id=? and wash_mode_id=4"
	mysqlHelper := db.GetQKLeagueMySQLHelper()
	_, err := mysqlHelper.Exec(sql, dt.QBA,dt.WasherId)
	sql1 := "update washing_mode set qbcoin=? where washer_id=? and wash_mode_id=2"
	mysqlHelper.Exec(sql1, dt.QBB,dt.WasherId)
	sql2 := "update washing_mode set qbcoin=? where washer_id=? and wash_mode_id=1"
	mysqlHelper.Exec(sql2, dt.QBC,dt.WasherId)
	sql3 := "update washing_mode set qbcoin=? where washer_id=? and wash_mode_id=3"
	db.GetQKLeagueMySQLHelper()
	mysqlHelper.Exec(sql3, dt.QBD,dt.WasherId)
	return err

}
func (p *adminService) ChangeWasherCardPrice(dt *QKWasherPrice) error {
	sql := "update washing_mode set cardcoin=? where washer_id=? and wash_mode_id=4"
	mysqlHelper := db.GetQKLeagueMySQLHelper()
	_, err := mysqlHelper.Exec(sql, dt.CardA,dt.WasherId)
	sql1 := "update washing_mode set cardcoin=? where washer_id=? and wash_mode_id=2"
	mysqlHelper.Exec(sql1, dt.CardB,dt.WasherId)
	sql2 := "update washing_mode set cardcoin=? where washer_id=? and wash_mode_id=1"
	mysqlHelper.Exec(sql2, dt.CardC,dt.WasherId)
	sql3 := "update washing_mode set cardcoin=? where washer_id=? and wash_mode_id=3"
	db.GetQKLeagueMySQLHelper()
	mysqlHelper.Exec(sql3, dt.CardD,dt.WasherId)
	return err

}
func (p *adminService) GetSomeWasher(washerId string) (error, *QKLWasher) {
	dtq := p.washerDtq("", "", washerId)
	sql, val := dtq.GenerateSQL()
	mysqlHelper := db.GetQKLeagueMySQLHelper()
	results, err := mysqlHelper.Query(sql, val...)
	if err == nil {
		if len(results) == 0 {
			log.Warnf("查询没有包含此类信息的洗衣机 GetSomeWasher err, washerId:%s", washerId)
			return errors.New("查询没有包含此类信息的洗衣机"), nil
		}
		return nil, p.washerParseRecords(mysqlHelper, results[0])
	} else {
		log.Errorf("mysql err sql:%s, err:%s", sql, err.Error())
	}
	return errors.New("数据库查询失败"), nil
}

func getActiveTime(imei string) string {
	sql := fmt.Sprintf("%s where imei = %s", "select reg_tick from washer_imei", imei)
	log.Debug(sql)
	mysqlHelper := db.GetQKLeagueMySQLHelper()
	results, err := mysqlHelper.Query(sql)
	if err == nil && len(results) > 0 {
		regTick := mysqlHelper.GetColInt64(results[0], "reg_tick")
		tm := time.Unix(regTick, 0)
		return tm.Format("2006-01-02 15:04:05")
	}
	return ""
}

func (p *adminService) washerDtq(leagueId, washRoomId, washerId string) *datatable.DataTableQuery {
	dtq := datatable.NewDataTableQuery()
	dtq.SetTableName("washer_info")
	dtq.PushField(&datatable.FiledItem{Alias: "washer_id", Field: "washer_id"})
	dtq.PushField(&datatable.FiledItem{Alias: "room_id", Field: "room_id"})
	dtq.PushField(&datatable.FiledItem{Alias: "imei", Field: "imei"})
	dtq.PushField(&datatable.FiledItem{Alias: "deploy_type", Field: "deploy_type"})
	dtq.PushField(&datatable.FiledItem{Alias: "admin_uid", Field: "admin_uid"})
	dtq.PushField(&datatable.FiledItem{Alias: "lat", Field: "lat"})
	dtq.PushField(&datatable.FiledItem{Alias: "lng", Field: "lng"})
	dtq.PushField(&datatable.FiledItem{Alias: "seqnum", Field: "seqnum"})
	dtq.PushField(&datatable.FiledItem{Alias: "addr_detail", Field: "addr_detail"})
	dtq.PushField(&datatable.FiledItem{Alias: "is_test", Field: "is_test"})
	dtq.PushField(&datatable.FiledItem{Alias: "enable", Field: "enable"})
	dtq.PushField(&datatable.FiledItem{Alias: "deposit", Field: "deposit"})
	dtq.PushField(&datatable.FiledItem{Alias: "insert_tick", Field: "insert_tick"})

	if washerId != "" {
		dtq.PushCondition("washer_id=?", washerId)
	} else {
		if washRoomId != "" {
			dtq.PushCondition("room_id=?", washRoomId)
		} else {
			_, rooms := getWashRoomNumByLeagueId(leagueId)
			if rooms != nil && len(rooms) != 0 {
				dtq.PushCondition("room_id in ?", rooms)
			}
		}
	}

	return dtq
}

func (p *adminService) washerParseRecords(mysqlHelper *utility.MySQLHelper, dt map[string]interface{}) *QKLWasher {
	li := &QKLWasher{}
	li.WasherId = mysqlHelper.GetColString(dt, "washer_id")
	li.WashRoomId = mysqlHelper.GetColString(dt, "room_id")
	li.IMEI = mysqlHelper.GetColString(dt, "imei")
	li.DeployType = mysqlHelper.GetColInt(dt, "deploy_type")
	li.AdminUid = mysqlHelper.GetColString(dt, "admin_uid")
	li.Lat = mysqlHelper.GetColString(dt, "lat")
	li.Lng = mysqlHelper.GetColString(dt, "lng")
	li.SeqNum = mysqlHelper.GetColInt(dt, "seqnum")
	li.AddrDetail = mysqlHelper.GetColString(dt, "addr_detail")
	li.IsTest = mysqlHelper.GetColInt(dt, "is_test")
	li.EnAble = mysqlHelper.GetColInt(dt, "enable")
	li.Deposit = mysqlHelper.GetColInt(dt, "deposit")
	insertTick := mysqlHelper.GetColInt64(dt, "insert_tick")
	tm := time.Unix(insertTick, 0)
	li.InsertTime = tm.Format("2006-01-02 15:04:05")

	_, washRoomInfos := p.GetSomeWashRoom("", li.WashRoomId, 0)
	if washRoomInfos != nil && len(washRoomInfos) != 0 {
		li.WashRoomName = washRoomInfos[0].WashRoomName

		li.LeagueId = washRoomInfos[0].LeagueId
		li.LeagueName = washRoomInfos[0].LeagueName
	}

	li.ActiveTime = getActiveTime(li.IMEI)

	if ok, runState := rpc.ObtainWasherStateByWasherId(li.WasherId); ok {
		rs := runState.(map[string]interface{})
		if val, ok := rs["wash_mode_msg"]; ok {
			li.RunState = val.(string)
		}
		if val, ok := rs["ws_show_msg"]; ok {
			if li.RunState != "" {
				li.RunState += "-" + val.(string)
			} else {
				li.RunState = val.(string)
			}
		}
	} else {
		log.Errorf("query washer run_state err, washer_id :%s", li.WasherId)
	}

	return li
}
